<template>
  <div>
    <el-dialog v-drag  width="90%" :title="!dataForm.priceListId ? '新增' : '修改'" :close-on-click-modal="false" :visible.sync="visible">
      <el-form :model="dataForm" :inline="true" :rules="dataRule" ref="dataForm" @keyup.enter.native="dataFormSubmit()"
        label-width="100px">
        <el-form-item label="划价单号" prop="priceListNo">
          <el-input size="mini" v-model="dataForm.priceListNo" placeholder="划价单号" disabled clearable></el-input>
        </el-form-item>
        <el-form-item label="划价单名称" prop="priceListName">
          <el-input size="mini" v-model="dataForm.priceListName" placeholder="划价单名称" clearable></el-input>
        </el-form-item>
        <el-form-item label="主治功能" prop="indicationDesc">
          <el-input size="mini" v-model="dataForm.indicationDesc" placeholder="主治功能" clearable></el-input>
        </el-form-item>
        <el-form-item label="处方单URL" prop="prescriptionUrl">
          <el-input size="mini" v-model="dataForm.prescriptionUrl" placeholder="处方单URL" clearable></el-input>
        </el-form-item>
        <el-form-item label="审核人" prop="auditUser">
          <el-select size="mini" @focus="getUsers()" @change="setUsers()" v-model="dataForm.auditUser" clearable
            placeholder="请选择">
            <el-option v-for="item in users" :key="item.userId" :label="item.username" :value="item.username">
            </el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="复核人" prop="reviewer">
          <el-select size="mini" @focus="getUsers()" @change="setUsers()" v-model="dataForm.reviewer" clearable
            placeholder="请选择">
            <el-option v-for="item in users" :key="item.userId" :label="item.username" :value="item.username">
            </el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="备注" prop="remark">
          <el-input size="mini" v-model="dataForm.remark" placeholder="备注" clearable></el-input>
        </el-form-item>

        <!-- 子表 -->
        <el-divider></el-divider>
        <el-form-item>
          <el-button class="line-button" size="mini" circle type="primary" @click="addRow()"><span
              class="icon iconfont">&#xe664;</span></el-button>
         <el-button class="line-button" size="mini" circle type="danger" @click="deleteRows()"><span
              class="icon iconfont">&#xe813;</span></el-button>
        </el-form-item>

        <el-table :data="dataForm.itemList" border size="mini" class="item-table" height="250"
          @selection-change="selectionChangeHandle" ref="itemTable"
          :header-cell-style="{ background: '#fcfcfc', color: '#606266', height:'36px'}">
          <el-table-column type="selection" header-align="center" align="center" width="50">
          </el-table-column>
          <el-table-column prop="productCode" header-align="center" width="150" align="center" label="药品编码">
            <template slot-scope="scope">
                <div class="product-code-box" v-if="scope.row.productCode == ''">
                  <el-form-item :prop="'itemList.'+scope.$index+'.productCode'" :rules="dataRule.productCode">
                    <el-input size="mini" v-model="scope.row.productCode" disabled class="product-code-input"
                      @blur='blurInput(scope.row, "productCode", scope.row.productCode)' v-focus>
                    </el-input>
                  </el-form-item>
                  <el-button size="mini" class="chose-button"  @click="selectproduct(scope.row)"><span
                      class="icon iconfont">&#xe68e;</span></el-button>
                </div>
              <span v-else>{{scope.row.productCode}}</span>
            </template>
          </el-table-column>
          <el-table-column prop="productName" header-align="center" width="180" align="center" label="药品名称">
          </el-table-column>
          <el-table-column prop="salePrice" header-align="center" width="130" align="center" label="售价">
          </el-table-column>
          <el-table-column prop="retailPrice" header-align="center" width="130" align="center" label="指导价">
          </el-table-column>
          <el-table-column prop="detailNum" header-align="center" width="130" align="center" label="划价数量">
            <template slot-scope="scope">
              <el-form-item :prop="'itemList.'+scope.$index+'.detailNum'" :rules="dataRule.detailNum">
                <el-input size="mini" v-model="scope.row.detailNum"
                type="number" :min="1"  oninput="value=value.replace(/^0|[^0-9]/g, '')"
                  @blur='blurInput(scope.row, "detailNum", scope.row.detailNum)' v-focus> </el-input>
              </el-form-item>
            </template>
          </el-table-column>
          <el-table-column prop="memberPrice" header-align="center" width="100" align="center" label="会员价">
          </el-table-column>
          <el-table-column prop="barCode" header-align="center" width="120" align="center" label="条码">
          </el-table-column>
          <el-table-column prop="genericName" header-align="center" width="180" align="center" label="通用名称">
          </el-table-column>
          <el-table-column prop="standard" header-align="center" width="140" align="center" label="规格">
          </el-table-column>
          <el-table-column prop="unit" header-align="center" align="center" label="单位">
          </el-table-column>
          <el-table-column prop="producingArea" header-align="center" width="180" align="center" label="产地">
          </el-table-column>
          <el-table-column prop="produceFactory" header-align="center" width="180" align="center" label="生产单位">
          </el-table-column>
          <el-table-column prop="approvalNo" header-align="center" width="140" align="center" label="批准文号">
          </el-table-column>
          <el-table-column prop="dosageForm" header-align="center" width="160" align="center" label="剂型">
          </el-table-column>
          <el-table-column prop="remark" header-align="center" width="150" align="center" label="备注">
            <template slot-scope="scope">
              <el-input size="mini" v-model="scope.row.remark" type="textarea"
                @blur='blurInput(scope.row, "remark", scope.row.remark)' autosize>
              </el-input>
            </template>
          </el-table-column>
          <el-table-column fixed="right" align="center" label="操作" width="100">
            <template slot-scope="scope">
              <el-button size="mini" type="danger" icon="el-icon-minus" class="delete-button"
                @click.native.prevent="deleteRow(scope.$index)"></el-button>
            </template>
          </el-table-column>
        </el-table>
      </el-form>
      <span slot="footer" class="dialog-footer">
        <el-button size="mini" @click="visible = false">取消</el-button>
        <el-button size="mini" type="primary" @click="dataFormSubmit()">确定</el-button>
      </span>
    </el-dialog>
    <!-- 弹窗, 新增 / 修改 -->
    <product-select v-if="productSelectVisible" ref="productSelectRef" @refreshDataList=""></product-select>
  </div>
</template>

<script>
  import cloneDeep from 'lodash/cloneDeep'
  import ProductSelect from '@/views/components/product-select.vue'
  export default {
    components: {
      ProductSelect
    },
    data() {
      var checkNum = (rule, value, callback) => {
        if (!value || value < 1) {
          return callback(new Error('数量不能<1'));
        } else {
          callback();
        }
      };
      return {
        visible: false,
        dataForm: {
          priceListId: 0,
          priceListNo: '',
          priceListName: '',
          indicationDesc: '',
          prescriptionUrl: '',
          auditorId: '',
          auditUser: '',
          reviewerId: '',
          reviewer: '',
          remark: '',
          itemList: []
        },
        productSelectVisible: false,
        users:[],
        oldData: {},
        showInput: "",
        dataListSelections: [],
        currentProduct: {},
        dataRule: {
          priceListNo: [{
            required: true,
            message: '划价单号不能为空',
            trigger: 'blur'
          }],
          priceListName: [{
            required: true,
            message: '划价单名称不能为空',
            trigger: 'blur'
          }],
          indicationDesc: [{
            required: true,
            message: '主治功能不能为空',
            trigger: 'blur'
          }],
          auditUser: [{
            required: true,
            message: '审核人不能为空',
            trigger: 'blur'
          }],
          reviewer: [{
            required: true,
            message: '复核人不能为空',
            trigger: 'blur'
          }],
          detailNum: [{
            required: true,
            validator: checkNum,
            trigger: 'blur'
          }],
        }
      }
    },
    watch: {
      currentProduct: {
        handler(obj, oldVal) {
          let product = {}
          product.productId = obj.productId;
          product.productCode = obj.productCode;
          product.productName = obj.productName;
          product.barCode = obj.barCode;
          product.genericName = obj.genericName;
          product.standard = obj.standard;
          product.unit = obj.unit;
          product.producingArea = obj.producingArea;
          product.produceFactory = obj.produceFactory;
          product.approvalNo = obj.approvalNo;
          product.dosageForm = obj.dosageForm;
          product.retailPrice = obj.retailPrice;
          product.salePrice = obj.salePrice;
          product.memberPrice = obj.memberPrice;
          product.detailNum = 0;
          product.rowNum = new Date().getTime()
          product.remark = '';
          let isAdd = false;
          let itemList = this.dataForm.itemList
          itemList.forEach((item, index) => {
            if (item.productCode === product.productCode || item.barCode === product.barCode) {
              isAdd = true;
              this.$message.error("[" + item.productCode + "]该药品已经添加！")
              return;
            }
            if (!item.productCode) {
              itemList.splice(index, 1)
            }
          })
          if (!isAdd) {
            itemList.push(product)
            this.dataForm.itemList = itemList
          }
        },
        immediate: true
      }
    },
    methods: {
      init(priceListId) {
        this.dataForm.itemList = []
        this.dataForm.priceListId = priceListId
        this.visible = true
        this.$nextTick(async () => {
          this.$refs['dataForm'].resetFields()
          if (this.dataForm.priceListId) {
            const res = await this.$http({
              url: `/sale/salepricelist/info/${this.dataForm.priceListId}`,
              method: 'get',
              params: this.$http.adornParams()
            })
            let data = res.data
            if (data && data.code === 0) {
              this.dataForm = data.salePriceList
            }
          }else {
            const res = await this.$http({
              url: `/sale/salepricelist/getOrderNo`,
              method: 'get',
              params: this.$http.adornParams()
            })
            let data = res.data
            if (data && data.code === 0) {
              this.dataForm.priceListNo = data.data
              this.addRow()
            }
          }
        })
      },
      // 表单提交
      dataFormSubmit() {
        this.$refs['dataForm'].validate(async (valid) => {
          if (valid) {
            this.dataForm.itemList.forEach((item, index) => {
              item.status = 1
              if(!item.productCode || !item.barCode){
                this.dataForm.itemList.splice(index, 1)
              }
            })
            console.log("this.dataForm==" , this.dataForm)
            const res = await this.$http({
              url: `/sale/salepricelist/${!this.dataForm.priceListId ? 'saveOrder' : 'updateOrder'}`,
              method: 'post',
              data: this.$http.adornData(this.dataForm)
            })
            let data = res.data
            if (data && data.code === 0) {
              this.$message({
                message: '操作成功',
                type: 'success',
                duration: 1500,
                onClose: () => {
                  this.visible = false
                  this.$emit('refreshDataList')
                }
              })
            } else {
              this.$message.error(data.msg)
            }
          }
        })
      },
      addRow() {
        let item = {
          rowNum: new Date().getTime(),
          detailId: undefined,
          priceListId: '',
          productId: '',
          productCode: '',
          genericName: '',
          standard: '',
          unit: '',
          producingArea: '',
          produceFactory: '',
          approvalNo: '',
          dosageForm: '',
          barCode: '',
          retailPrice: 0,
          salePrice: 0,
          memberPrice: 0,
          detailNum: 0,
          remark: ''
        }
        this.dataForm.itemList.push(item)
      },
      deleteRows() {
        this.dataListSelections.forEach((val, index) => {
          this.dataForm.itemList.forEach((v, i) => {
            if (val.rowNum === v.rowNum) {
              // i 为选中的索引
              this.dataForm.itemList.splice(i, 1)
            }
          })
        })
        // 删除完数据之后清除勾选框
        this.$refs.itemTable.clearSelection()
      },
      //第三：点击 — 号执行删除一行的方法
      deleteRow(index) {
        //利用数组的splice方法，将该index数据删除
        this.dataForm.itemList.splice(index, 1);
      },
      selectionChangeHandle(val) {
        this.dataListSelections = val
      },
      selectproduct(row) {
        this.productSelectVisible = true
        this.$nextTick(() => {
          this.$refs.productSelectRef.init()
        })
      },
      blurInput(row, name, value) {
        // 判断数据是否有所改变，如果数据有改变则调用修改接口
        if (this.oldData[name] != value) {
          row[name] = value
        }
        this.showInput = ""
      },
      async getUsers() {
        const res = await this.$http({
          url: `/sys/user/listUsers`,
          method: 'get',
          params: this.$http.adornParams()
        })
        let data = res.data
        if (data && data.code === 0) {
          this.users = data.data
        }
      },
      setUsers() {
        this.users.forEach((item) => {
          if (this.dataForm.auditUser == item.username) {
            this.dataForm.auditUserId = item.userId ? item.userId : 1
          } else if (this.dataForm.reviewer == item.username) {
            this.dataForm.reviewerId = item.userId ? item.userId : 1
          }
        });
      },
      async getDicts(type) {
        const res = await this.$http({
          url: '/base/basedict/getDict',
          method: 'get',
          params: this.$http.adornParams({
            'code': type
          })
        })
        let data = res.data
        if (data && data.code === 0) {
          if (type === 'PAY_METHOD') {
            this.paymentMethods = data.data
          }
        }
      },
    },
    directives: {
      // 通过自定义指令实现的表单自动获得光标的操作
      focus: {
        inserted: function(el) {
          if (el.tagName.toLocaleLowerCase() == "input") {
            el.focus()
          } else {
            if (el.getElementsByTagName("input")) {
              el.getElementsByTagName("input")[0].focus()
            }
          }
          el.focus()
        }
      },
      focusTextarea: {
        inserted: function(el) {
          if (el.tagName.toLocaleLowerCase() == "textarea") {
            el.focus()
          } else {
            if (el.getElementsByTagName("textarea")) {
              el.getElementsByTagName("textarea")[0].focus()
            }
          }
          el.focus()
        }
      }
    }
  }
</script>
<style lang="less" scoped>
  .el-dialog__body {
    padding: 5px 20px 30px 20px;
  }

  .product-code-box {
    display: flex;
    justify-content: right;
    align-items: center;

    .product-code-input {
      background-color: #fff;

      .el-input__inner {
        border: 0px !important;
        background-color: #fff;
      }
    }
    .chose-button {
      margin: 0 0 10px 0;
      height: 30px;
      width: 18px;
      padding: 3px 1px;
      margin-left: 2px;
      background-color: #e4f3f7;
    }
  }

  .el-divider {
    margin-bottom: 5px;
  }

  .icon {
    margin-right: 0px;
  }

  .delete-button {
    padding: 3px 5px;
  }

  .el-textarea__inner {
    line-height: 1 !important;
  }
  .el-date-picker{
    width: 100%;
  }

  .el-date-editor.el-input, .el-date-editor.el-input__inner {
     width: auto;
  }

  .el-form-item__error{
    padding-top: 0px!important;
    z-index: 99;
  }

  .el-table{
    // .el-form-item {
    //   margin: 0px;
    //   padding: 0px;
    // }

  }


</style>
